const express = require('express')
const router = express.Router()

//导入数据库 sqlFun('sql语句',数组格式的参数,res=>{})
const sqlFn = require('./mysql')
//图片需要的模块
const multer = require('multer')
const fs = require('fs')

//路由接口

router.get('/', (req, res) => {
    res.send("hello")
})

//商品数据   查询列表   page:分页    data:数据信息  pageSize：规定条数  total总共数据条数

router.get('/projectList', (req, res) => {
    const page = req.query.page || 1;
    const sqlNum = "select * from websites"
    sqlFn(sqlNum, null, data => {
        let len = data.length;
        const sqlLen = `SELECT * FROM websites ORDER BY id ASC LIMIT 5 OFFSET ${(page - 1) * 5}`;    // limit （限制长度） offset 保留多少
        sqlFn(sqlLen, null, result => {

            if (result.length > 0) {
                res.send({
                    status: 200,
                    data: result,
                    pageSize: 5,
                    total: len,
                })
            } else {
                res.send({
                    status: 500,
                    msg: "暂无数据"
                })
            }

        })
    })


})


router.get('/search', (req, res) => {
    const search = req.query.search;
    // const sqlNum = `SELECT * FROM websites`

        const sql = `SELECT * FROM websites WHERE title LIKE '%${search}%'`;    // limit （限制长度） offset 保留多少
        sqlFn(sql, null, result => {

            if (result.length > 0) {
                res.send({
                    status: 200,
                    data: result
                })
            } else {
                res.send({
                    status: 500,
                    msg: "暂无数据"
                })
            }

        })
    


})

// 类目选择
router.get("/category",(req,res) =>{
    const id = req.query.id || 1;
    const sql = "select * from category where id=?"
    var arr = [id];
    sqlFn(sql,arr,result =>{
        if(result.length>0){
            res.send({
                status:200,
                result
            })
        }else{
            res.send({
                status:500,
                msg:"暂无数据"
            })
        }
    })
})

// 类目结构数据获取
router.get("/subcategory",(req,res) =>{
    const uid = req.query.uid || 1;
    const sql = "select * from subcategory where uid=?";
    sqlFn(sql,[uid],result =>{
        if(result.length>0){
            res.send({
                status:200,
                result
            })
        }else{
            res.send({
                status:500,
                msg:"暂无数据"
            })
        }
    })
})

// 上传图片 post请求 upload
//  说明:
// 1.后台安装 multer 模块 同时引入fs模块
// 2.router.js入口文件导入模块
//    const fs = require("fs")
//       const multer = require("multer")
//    3.上传图片
var storage = multer.diskStorage({
    destination:function (req,file,cb){
        cb(null,"./upload/")
    },
    filename:function (req,file,cb){
        cb(null,Date.now() + "-" + file.originalname)
    }
})

var createFolder = function (folder){
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}

var uploadFolder = "./upload/";
createFolder(uploadFolder);
var upload = multer({
    storage:storage
});

router.post("/upload",upload.single('file'),function (req,res,next){
    var file = req.file;
    // console.log("文件类型,%s",file.mimetype)
    // console.log("原始文件名",file.originalname)
    // console.log("文件大小",file.size)
    // console.log("文件保存路径",file.path)
    res.json({
        res_code:"0",
        name:file.originalname,
        url:file.path,
    });
})


// 商品添加 参数 title cid category price num desc image
router.get("/addGoods",(req,res)=>{
    //获取参数
    var title = req.query.title || "";
    var category = req.query.category || "";
    var sellPoint = req.query.sellPoint || "";
    var price = req.query.price || "";
    var num = req.query.num || "";
    var desc = req.query.desc || "";
    var image = req.query.image || "";

    var sql =`INSERT INTO websites(title,price,num,category,image,sellPoint) VALUES (\"${title}\",\"${price}\",${num},\"${category}\",\"${image}\",\"${sellPoint}\")`

    var arr = [title,image,sellPoint,price,category,num,desc];

    sqlFn(sql, arr, result => {

        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg:"添加成功"

            })
        } else {
            res.send({
                status: 500,
                msg: "添加失败"
            })
        }

    })

})

module.exports = router